<?php
    namespace app\Capital\admin;
    use app\admin\controller\Admin;
    use app\common\builder\ZBuilder;
    use think\Model;
    use think\Db;
    use app\Capital\model\capital as CapitalModel;
    use app\Capital\model\account;
    class Adjustment extends Admin
    {

        //会员账务调整
        public function index()
        {
            $map = $this->getMap();
            $status = input('status');
            if (99 == $status) {
                $map['status'] = 0;
            }
            $map['user_type'] = 1;
            $list_tab = [
                'tab1' => ['title' => '会员账务调整列表', 'url' => url('index')],
                'tab2' => ['title' => '店铺账务调整列表', 'url' => url('shop_adjustment')],
            ];
         $data = Db::name("accounting_adjustment")->where($map)->order('id desc')->select();
            return ZBuilder::make('table')
                ->setTabNav($list_tab, 'tab1')
                ->hideCheckbox()
                ->setSearch(['id' => '单据ID', 'no' => '单据号', 'name' => '用户名称'])
                ->addColumns([
                    ['no', '单据号'],
                    ['name', '会员名称'],
                    ['num', '调整金额', 'callback', 'getPrice'],
                    ['type', '调整原因', 'type', '', CapitalModel::get_type(7)],
                    ['createtime', '创建时间', 'datetime'],
                ])
                ->addColumn('status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
                ->addColumn('right_button', '操作', 'btn')
                ->addTopButton('add', ['title' => '新增', 'table' => '', 'href' => url('member_adjustment_add')])
                ->addTopButton('custom', ['title' => '待审核', 'icon' => 'fa fa-fw fa-cogs', 'href' => url('index', ['status' => 99])])
                ->addRightButton('custom', ['title' => '修改单据', 'icon' => 'fa fa-wrench','href'=>url('adjustment_edit',['id'=>'__id__','user_type'=>1])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '单据查看', 'icon' => 'fa fa-eye','href'=>url('adjustment_see',['id'=>'__id__','user_type'=>1])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '审核单据', 'icon' => 'fa fa-fw fa-question-circle','href'=>url('member_examine',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addTimeFilter('createtime')
                ->setRowList($data)
                ->fetch();

        }

        //店铺账务调整
        public function shop_adjustment()
        {
            $map = $this->getMap();
            $status = input('status');
            if (99 == $status) {
                $map['status'] = 0;
            }
            $map['user_type'] = 2;
            $list_tab = [
                'tab1' => ['title' => '会员账务调整列表', 'url' => url('index')],
                'tab2' => ['title' => '店铺账务调整列表', 'url' => url('shop_adjustment')],
            ];
            $data = Db::name("accounting_adjustment")->where($map)->order('id desc')->select();
            return ZBuilder::make('table')
                ->setTabNav($list_tab, 'tab2')
                ->hideCheckbox()
                ->setSearch(['id' => '单据ID', 'no' => '单据号', 'name' => '用户名称'])
                ->addColumns([
                    ['no', '单据号'],
                    ['name', '店铺名称'],
                    ['num', '调整金额', 'callback', 'getPrice'],
                    ['type', '调整原因', 'type', '', CapitalModel::get_type(7)],
                    ['createtime', '创建时间', 'datetime'],
                ])
                ->addColumn('status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
                ->addColumn('right_button', '操作', 'btn')
                ->addTopButton('add', ['title' => '新增', 'table' => '', 'href' => url('shop_adjustment_add')])
                ->addTopButton('custom', ['title' => '待审核', 'icon' => 'fa fa-fw fa-cogs', 'href' => url('shop_adjustment', ['status' => 99])])
                ->addRightButton('custom', ['title' => '修改单据', 'icon' => 'fa fa-wrench','href'=>url('adjustment_edit',['id'=>'__id__','user_type'=>2])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '单据查看', 'icon' => 'fa fa-eye','href'=>url('adjustment_see',['id'=>'__id__','user_type'=>2])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '审核单据', 'icon' => 'fa fa-fw fa-question-circle','href'=>url('shop_examine',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addTimeFilter('createtime')
                ->setRowList($data)
                ->fetch();
        }

        //新建会员账务调整单
        public function member_adjustment_add()
        {
            $js = <<<EOF
            <script type="text/javascript">
            $(document)
               .off('blur','#num')
               .on('blur','#num',function(){
               //只能输入数字
               var str = $('#num').val();
               var reg1 = (/^([+-]?[\d]+[.]\d{0,2})$/gi).test(str);
               var reg2 = (/^([+-]?[\d]+)$/gi).test(str);
               if(reg1||reg2){
                  $(this).css('background',"#fff");
               }else{
                  $(this).val('');
               }
               if(!str){
                     return false;
               }
            })
            </script>
EOF;
            return ZBuilder::make('form')
                ->setPageTitle('新建会员账户调整单')
                ->addSelect('userid', '会员', '', '', '', 'ajax', '', ['url' => '/admin.php/capital/adjustment/adjustment_list/type/1', 'datakey' => 'id', 'dataname' => 'name'])
                ->addText('num', '调整金额')
                ->addSelect('type', '调整原因', '', CapitalModel::get_type(7))
                ->addTextarea('notes','备注')
                ->layout(['userid' => 4, 'num' => 4, 'type' => 4])
                ->setUrl(url('allsave', ['user_type' => 1]))
                ->setExtrajs($js)
                ->fetch();
        }

        //新建店铺账务调整单
        public function shop_adjustment_add()
        {
            return ZBuilder::make('form')
                ->setPageTitle('新建店铺账户调整单')
                ->addSelect('userid', '店铺', '', '', '', 'ajax', '', ['url' => '/admin.php/capital/adjustment/adjustment_list/type/2', 'datakey' => 'id', 'dataname' => 'name'])
                ->addText('num', '调整金额', '', '', '', 'onkeyup="if(isNaN(value))execCommand(\'undo\')"  onafterpaste="if(isNaN(value))execCommand(\'undo\')"', '')
                ->addSelect('type', '调整原因', '', CapitalModel::get_type(7))
                ->addTextarea('notes','备注')
                ->layout(['userid' => 4, 'num' => 4, 'type' => 4])
                ->setUrl(url('allsave', ['user_type' => 2]))
                ->fetch();
        }


        public function adjustment_list()
        {
            $type = input('type');
            $serach = input("q");
            if (1 == $type) {
                $table = "member";
                $where['company'] = ['like', "%$serach%"];
            } elseif (2 == $type) {
                $table = "shop";
                $where['name'] = ['like', "%$serach%"];
            } else {
                return false;
            }
            $data = Db::name($table)->where($where)->select();
            $member = [];
            $a = 0;
            foreach ($data as $value) {
                $b = $a++;
                if (1 == $type) {
                    $key = $value['id'] . '-' . $value['company'];
                    $member[$b]['id'] = $key;
                    $member[$b]['name'] = $value['company'];
                } elseif (2 == $type) {
                    $key = $value['id'] . '-' . $value['name'];
                    $member[$b]['id'] = $key;
                    $member[$b]['name'] = $value['name'];
                }

            }
            return json(['items' => $member, 'total_count' => sizeof($member)]);
        }
        //账户调整单保存

        public function allsave()
        {
            $data = input();
            if ($data) {
                if (0 == $data['type']) {
                    return $this->error("请选择调整单原因");
                } else {
                    $user = $data['userid'][0];
                    if ($user) {
                        $userArr = explode('-', $user);
                        $data['name'] = $userArr[1];
                        $data['userid'] = $userArr[0];
                        $No = date('YmdHis');
                        $data['createtime'] = time();
                        $result = $this->validate($data, 'Adjustment');
                        if (true !== $result) {
                            return $this->error($result);
                        }
                        $data['num'] = setPrice($data['num']);
                        $data['no'] = 'TZ-' . $data['userid'] . $No;
                        $result = Db::name("accounting_adjustment")->insert($data);
                        if ($result) {
                            if (1 == $data['user_type']) {
                                $url = 'index';
                            } else {
                                $url = 'shop_adjustment';
                            }
                            return $this->success("新增账户调整单成功", url($url));
                        } else {
                            return $this->error("新增账户调整单失败");
                        }
                    } else {
                        return $this->error("新增账户调整单失败");
                    }
                    return $this->error("新增账户调整单失败");
                }
            }
        }
        //单据查看

        public function adjustment_see(){
            $user_type=input('user_type');
            if(1==$user_type){
                $user="会员";
            }else{
                $user="店铺";
            }
            $id=input('id');
            $result=Db::name('accounting_adjustment')->where('id',$id)->find();
            $type=CapitalModel::get_type(7);
            $result['type']=$type[$result['type']];
            return   ZBuilder::make('form')
                ->setPageTitle($user.'账户调整单')
                ->addStatic('name', $user.'名称')
                ->addStatic('num', '调整金额')
                ->addStatic('type', '调整原因')
                ->addStatic('notes','备注')
                ->layout(['name' => 2, 'num' => 2, 'type' => 2])
                ->setFormData($result)
                ->hideBtn('submit,back')
                ->fetch();

        }

        //单据修改
        public function adjustment_edit(){
        $user_type=input('user_type');
        if(1==$user_type){
            $user="会员";
        }else{
            $user="店铺";
        }
        $id=input('id');
        if($id){
            $result=Db::name('accounting_adjustment')->where('id',$id)->find();
            if(0!=$result['status']){
                $this->error("已审核单据不能修改");
            }
        }else{
            return $this->error('单据编辑错误');
        }

 $js = <<<EOF
            <script type="text/javascript">
            $(document)
               .off('blur','#num')
               .on('blur','#num',function(){
               //只能输入数字
               var str = $('#num').val();
               var reg1 = (/^([+-]?[\d]+[.]\d{0,2})$/gi).test(str);
               var reg2 = (/^([+-]?[\d]+)$/gi).test(str);
               if(reg1||reg2){
                  $(this).css('background',"#fff");
               }else{
                  $(this).val('');
               }
               if(!str){
                     return false;
               }
            })
            </script>
EOF;

         return   ZBuilder::make('form')
                ->setPageTitle($user.'账户调整单')
                ->addStatic('name', $user.'名称')
                ->addText('num', '调整金额')
                ->addSelect('type', '调整原因', '', CapitalModel::get_type(7))
                ->addTextarea('notes','备注')
                ->layout(['name' => 2, 'num' => 4, 'type' => 4])
                ->setUrl(url('edit_save', ['id' => $id]))
                ->setFormData($result)
                ->setExtrajs($js)
                ->fetch();
        }

        public function edit_save(){
            $id=input('id');
            if($id){
                $data=input();
                $data['num']=setPrice($data['num']);
                $re=Db::name('accounting_adjustment')->where('id',$id)->update($data);
                if($re){
                    $this->success('单据修改成功',url('index'));
                }else{
                    $this->error('单据修改失败');
                }
            }else{
                $this->error('单据查找失败');
            }
        }
       //单据审核
        public function member_examine(){
            $id=input('id');
            if($id){
                    //会员账户调整单审核
                    $memebr_adjustment=Db::name('accounting_adjustment')->where('id',$id)->find();
                    if(0!=$memebr_adjustment['status']){
                        $this->error("已审核单据不能重复审核");
                    }
                    if($memebr_adjustment){
                        $member=Db::name('member')->where('id',$memebr_adjustment['userid'])->find();
                        Db::startTrans();
                        try{
                            $re=Db::name("accounting_adjustment")->where('id',$id)->setField('status',1);
                           // dump($re);exit();
                            if($re){
                                $num=$member['balance']+$memebr_adjustment['num'];
                                $result=Db::name("member")->where('id',$member['id'])->setField('balance',$num);
                                if($result){
                                    $data['no']=$memebr_adjustment['no'];
                                    $data['memberid']=$member['id'];
                                    $data['num']=$memebr_adjustment['num'];
                                    if(7==$memebr_adjustment['type']){
                                       $data['type']=7;
                                    }else{
                                        $data['type']=4;
                                    }
                                    $data['balance']=$member['balance'];
                                    $account=account::add_member_account($data);
                                    //     dump($account);exit();
                                    if($account){
                                        $msg='单据审核成功，会员余额已变更，交易数据已保存';
                                    }
                                }
                            }
                            // 提交事务
                            Db::commit();
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            $this->error('单据审核失败');
                        }
                        $this->success($msg);
                    }else{
                        $this->error("未找到对应的会员账户");
                    }

                }else{
                    $this->error('单据错误');

                }
            }
        //店铺调整单审核
        public function shop_examine(){
            $id=input('id');
            if($id) {
                $shop_adjustment = Db::name('accounting_adjustment')->where('id', $id)->find();
                if(0!=$shop_adjustment['status']){
                    $this->error("已审核单据不能重复审核");
                }
                if ($shop_adjustment) {
                    $shop = Db::name('shop')->where('id', $shop_adjustment['userid'])->find();
                    if($shop) {
                        Db::startTrans();
                        try {
                            $re = Db::name("accounting_adjustment")->where('id', $id)->setField('status', 1);
                            // dump($re);exit();
                            if ($re) {
                                $num = $shop['balance'] + $shop_adjustment['num'];
                                $result = Db::name("shop")->where('id', $shop['id'])->setField('balance', $num);
                                if ($result) {
                                    $data['no'] = $shop_adjustment['no'];
                                    $data['shopid'] = $shop['id'];
                                    $data['num'] = $shop_adjustment['num'];
                                    if (7 == $shop_adjustment['type']) {
                                        $data['type'] = 7;
                                    } else {
                                        $data['type'] = 4;
                                    }
                                    $data['balance'] = $shop['balance'];
                                    $account = account::add_shop_account($data);
                                    //     dump($account);exit();
                                    if ($account) {
                                        $msg = '单据审核成功，店铺余额已变更，交易数据已保存';
                                    }
                                }
                            }else{
                                $this->error("单据不能重复审核");
                            }
                            // 提交事务
                            Db::commit();
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                           $this->error('单据审核失败');
                        }
                        $this->success($msg);
                    }else{
                        $this->error("单据对应店铺账户未找到");
                    }
                } else {
                    $this->error("单据未找到");
                }
            }else{
                $this->error("单据错误");
            }
        }
}
